package com.example.litehdfs.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson2.JSON;
import com.example.litehdfs.util.UserCacheUtil;

@Component
public class AuthInterceptor implements HandlerInterceptor {
	@Autowired
	private UserCacheUtil cacheUtil;
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 登录拦截 
		String requestURI = request.getRequestURI();
		
		//分别拦截用户登录和管理员登录
		if(requestURI.startsWith("/admin")) {
			Long adminId = cacheUtil.getAdminId();
			if(adminId == null) {
				writer(response,ResponseMsg.of(CodeConstant.LOGIN_ERROR,"请重新登录",null));
				return false;
			}
		}else {
			Long userId = cacheUtil.getUserId();
			if(userId == null) {
				writer(response,ResponseMsg.of(CodeConstant.LOGIN_ERROR,"请重新登录",null));
				return false;
			}
			
		}
		return true;
	}

	private void writer(HttpServletResponse response,ResponseMsg msg) {
		 response.setCharacterEncoding("UTF-8");
         response.setContentType("application/json; charset=utf-8");
         response.setHeader("Access-Control-Allow-Origin", "*");
         response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
         response.setHeader("Access-Control-Max-Age", "3600");
         response.setHeader("Access-Control-Allow-Headers", "*");
         response.setHeader("Access-Control-Allow-Credentials", "true");

         try {
			response.getWriter().append(JSON.toJSONString(msg));
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(),e);
		}
	}
}
